<template>
  <div class="evaluation-page">
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 主选项卡导航 -->
       <el-tabs v-model="mainTab" @tab-change="handleMainTabClick">
        <!-- <el-tab-pane label="待评价" name="to-evaluate"></el-tab-pane> -->
        <!-- <el-tab-pane label="我的评价" name="my-evaluations"></el-tab-pane> -->
        <el-tab-pane label="同学评价" name="classmate-evaluations"></el-tab-pane>
      </el-tabs>
      
      <!-- 待评价内容 -->
      <div v-if="mainTab === 'to-evaluate'">
        <!-- 评价类型选择 -->
        <div class="mb-8">
          <el-tabs v-model="selectedType" @tab-click="handleTabClick">
            <el-tab-pane label="班干部评价" name="class"></el-tab-pane>
            <el-tab-pane label="宿管评价" name="dorm"></el-tab-pane>
          </el-tabs>
        </div>
        
        <!-- 人员列表 -->
        <el-card class="mb-6">
          <el-table :data="targets" stripe v-loading="loading">
            <el-table-column prop="name" label="姓名" width="120"></el-table-column>
            <el-table-column prop="role" label="职位" width="120"></el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="openEvaluationModal(row)"
                >
                  评价
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="mt-4 flex justify-center">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :page-size="pageSize"
              :current-page="currentPage"
              :total="totalTargets"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </div>
      
      <!-- 我的评价内容 -->
      <div v-if="mainTab === 'my-evaluations'">
        <el-card class="mb-6">
          <el-table :data="myEvaluations" stripe v-loading="loadingMyEvaluations">
            <el-table-column prop="targetName" label="评价对象" width="120"></el-table-column>
            <el-table-column prop="targetPosition" label="职位" width="120"></el-table-column>
            <el-table-column prop="score" label="总体评分" width="120"></el-table-column>
            <!-- <el-table-column  label="总体评分">
              <template #default="{ row }">
                <el-rate :value="Number(row.score)" :max="5" disabled show-score /> 
              </template>
            </el-table-column> -->
            <el-table-column prop="createTime" label="评价时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewMyEvaluation(row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="mt-4 flex justify-center">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :page-size="myEvaluationsPageSize"
              :current-page="myEvaluationsCurrentPage"
              :total="totalMyEvaluations"
              @current-change="handleMyEvaluationsPageChange"
            />
          </div>
        </el-card>
      </div>
      
      <!-- 同学评价内容 -->
      <div v-if="mainTab === 'classmate-evaluations'">
        <el-card class="mb-6">
          <!-- <el-input
  v-model="searchKeyword"
  placeholder="搜索同学或评价对象"
  clearable
  @keyup.enter="searchClassmateEvaluations" 
  class="mb-4"
  style="width: 300px"
/> -->
          
          <el-table :data="classmateEvaluations" stripe v-loading="loadingClassmateEvaluations">
            <el-table-column prop="evaluatorName" label="评价人" width="120"></el-table-column>
            <!-- <el-table-column prop="targetName" label="评价对象" width="120"></el-table-column> -->
            <el-table-column prop="score" label="总体评分">
              <!-- <template #default="{ row }">
                <el-rate :value="row.score" :max="5" disabled show-score />
              </template> -->
        
            </el-table-column>
            <el-table-column prop="createTime" label="评价时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewClassmateEvaluation(row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="mt-4 flex justify-center">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :page-size="classmateEvaluationsPageSize"
              :current-page="classmateEvaluationsCurrentPage"
              :total="totalClassmateEvaluations"
              @current-change="handleClassmateEvaluationsPageChange"
            />
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 评价表单模态框 -->
    <el-dialog
      title="评价表单"
      v-model="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form :model="evaluationForm" label-width="120px">
        <el-form-item label="评价对象">
          <span>{{ currentTarget.name || '-' }}</span>
          <span class="ml-2 text-sm text-gray-500">{{ currentTarget.position || '' }}</span>
        </el-form-item>
        
        <el-form-item label="总体评分">
          <el-rate v-model="evaluationForm.score" show-score :max="5" />
        </el-form-item>
        
        <el-form-item label="工作态度">
          <el-rate v-model="evaluationForm.attitude" show-score :max="5" />
        </el-form-item>
        
        <el-form-item label="工作能力">
          <el-rate v-model="evaluationForm.ability" show-score :max="5" />
        </el-form-item>
        
        <el-form-item label="沟通效率">
          <el-rate v-model="evaluationForm.communication" show-score :max="5" />
        </el-form-item>
        
        <el-form-item label="评价内容">
          <el-input 
            v-model="evaluationForm.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入评价内容（选填）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 我的评价详情模态框 -->
    <el-dialog
      title="评价详情"
      v-model="myEvaluationDialogVisible"
      width="700px"
    >
      <el-form label-width="120px">
        <el-form-item label="评价对象">
          <span>{{ myEvaluationDetail.targetName || '-' }}</span>
          <span class="ml-2 text-sm text-gray-500">{{ myEvaluationDetail.targetPosition || '' }}</span>
        </el-form-item>
        
        <el-form-item label="总体评分">
          <!-- <el-rate :value="myEvaluationDetail.score" :max="5" disabled show-score /> -->
           <span>{{ myEvaluationDetail.score }}</span>
        </el-form-item>
        
        <el-form-item label="工作态度">
          <!-- <el-rate :value="myEvaluationDetail.attitude" :max="5" disabled /> -->
           <span>{{ myEvaluationDetail.attitude }} </span>
        </el-form-item>
        
        <el-form-item label="工作能力">
          <!-- <el-rate :value="myEvaluationDetail.ability" :max="5" disabled /> -->
           <span>{{ myEvaluationDetail.ability }} </span>
        </el-form-item>
        
        <el-form-item label="沟通效率">
          <!-- <el-rate :value="myEvaluationDetail.communication" :max="5" disabled /> -->
           <span>{{ myEvaluationDetail.communication }} </span>
        </el-form-item>
        
        <el-form-item label="评价内容">
          <div class="bg-gray-50 p-3 rounded border border-gray-200">
            {{ myEvaluationDetail.content || '无具体评价内容' }}
          </div>
        </el-form-item>
        
        <el-form-item label="评价时间">
          <span>{{ formatDate(myEvaluationDetail.createTime) }}</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="myEvaluationDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 同学评价详情模态框 -->
    <el-dialog
      title="同学评价详情"
      v-model="classmateEvaluationDialogVisible"
      width="700px"
    >
      <el-form label-width="120px">
        <el-form-item label="评价人">
          <span>{{classmateEvaluationDetail.evaluatorName  || '-' }}</span>
        </el-form-item>
        
        <!-- <el-form-item label="评价对象">
          <span>{{ classmateEvaluationDetail.targetName || '-' }}</span>
          <span class="ml-2 text-sm text-gray-500">{{ classmateEvaluationDetail.targetPosition || '' }}</span>
        </el-form-item> -->
        
        <el-form-item label="总体评分">
          <!-- <el-rate :value="classmateEvaluationDetail.score" :max="5" disabled show-score /> -->
           <span>{{ classmateEvaluationDetail.score }} </span>
        </el-form-item>
        
        <el-form-item label="工作态度">
          <span>{{ classmateEvaluationDetail.attitude }} </span>
        </el-form-item>
        
        <el-form-item label="工作能力">
          <!-- <el-rate :value="classmateEvaluationDetail.ability" :max="5" disabled /> -->
           <span>{{ classmateEvaluationDetail.ability}} </span>
        </el-form-item>
        
        <el-form-item label="沟通效率">
          <!-- <el-rate :value="classmateEvaluationDetail.communication" :max="5" disabled /> -->
           <span>{{ classmateEvaluationDetail.communication}} </span>
           
        </el-form-item>
        
        <el-form-item label="评价内容">
          <div class="bg-gray-50 p-3 rounded border border-gray-200">
            {{ classmateEvaluationDetail.content || '无具体评价内容' }}
          </div>
        </el-form-item>
        
        <el-form-item label="评价时间">
          <span>{{ formatDate(classmateEvaluationDetail.createTime) }}</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="classmateEvaluationDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage ,ElTabPane} from 'element-plus';
import { useUserStore } from '@/store/user';
import { 
  getClassLeader, 
  getDormAdmin, 
  EvaluationSubmit, 
//   getStudentEvaluation,
  getMyEvaluations,
} from '@/api/student';

import {  getClassmateEvaluations } from '@/api/admin'

// 状态管理
const mainTab = ref('classmate-evaluations'); // 主选项卡：待评价、我的评价、同学评价
const selectedType = ref('class'); // 评价类型：班干部、宿管
// const searchKeyword = ref(''); // 搜索关键词

// 待评价列表
const targets = ref([]);
const totalTargets = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const isTabChanging = ref(false);

// 我的评价列表
const myEvaluations = ref([]);
const totalMyEvaluations = ref(0);
const myEvaluationsPageSize = ref(10);
const myEvaluationsCurrentPage = ref(1);
const loadingMyEvaluations = ref(false);
const myEvaluationDetail = ref({});
const myEvaluationDialogVisible = ref(false);

// 同学评价列表
const classmateEvaluations = ref([]);
const totalClassmateEvaluations = ref(0);
const classmateEvaluationsPageSize = ref(10);
const classmateEvaluationsCurrentPage = ref(1);
const loadingClassmateEvaluations = ref(false);
const classmateEvaluationDetail = ref({});
const classmateEvaluationDialogVisible = ref(false);

const userStore = useUserStore();

// 评价表单
const dialogVisible = ref(false);
const currentTarget = ref({});
const evaluationForm = ref({
  score: 5,
  attitude: 5,
  ability: 5,
  communication: 5,
  content: ''
});

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 处理主选项卡点击
// const handleMainTabClick = async (activeName) => {
//   console.log('Selected tab name:', activeName); // 应输出 'to-evaluate' 或 'my-evaluations'
  
  
//   // 加载对应选项卡的数据
//   if (activeName === 'to-evaluate') {
//     await fetchTargets();
//   } else if (activeName === 'my-evaluations') {
//     await fetchMyEvaluations();
//   } else if (activeName === 'classmate-evaluations') {
//     await fetchClassmateEvaluations();
//   }
// };

// 处理评价类型标签点击
const handleTabClick = async (tab) => {
  console.log('Evaluation type tab clicked:', tab.name);
  
  if (isTabChanging.value) return;
  
  isTabChanging.value = true;
  
  try {
    selectedType.value = tab.name;
    currentPage.value = 1;
    await nextTick();
    await fetchTargets();
  } catch (error) {
    console.error('标签切换错误:', error);
  } finally {
    isTabChanging.value = false;
  }
};

// 获取班干部列表
const fetchClassLeaders = async () => {
  loading.value = true;
  try {
    const params = {
      studentId: userStore.userInfo.studentId,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    console.log('请求班干部列表参数:', params);
    const response = await getClassLeader(params);
    console.log('班干部列表响应数据:', response);
    
    if (response.code === 0) {
      targets.value = response.data.items || [];
      totalTargets.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取班干部列表失败');
      targets.value = [];
      totalTargets.value = 0;
    }
  } catch (error) {
    console.error('获取班干部列表失败:', error);
    ElMessage.error('网络错误，请重试');
    targets.value = [];
    totalTargets.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取宿管列表
const fetchDormManagers = async () => {
  loading.value = true;
  try {
    const params = {
      studentId: userStore.userInfo.studentId,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    console.log('请求宿管列表参数:', params);
    const response = await getDormAdmin(params);
    console.log('宿管列表响应数据:', response);
    
    if (response.code === 0) {
      targets.value = response.data.items || [];
      totalTargets.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取宿管列表失败');
      targets.value = [];
      totalTargets.value = 0;
    }
  } catch (error) {
    console.error('获取宿管列表失败:', error);
    ElMessage.error('网络错误，请重试');
    targets.value = [];
    totalTargets.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取人员列表
const fetchTargets = async () => {
  console.log("切换到:", selectedType.value);
  
  if (selectedType.value === 'class') {
    await fetchClassLeaders();
  } else {
    await fetchDormManagers();
  }
};

// 获取我的评价列表
const fetchMyEvaluations = async () => {
  loadingMyEvaluations.value = true;
  try {
    const params = {
      studentId: userStore.userInfo.studentId,
      page: myEvaluationsCurrentPage.value,
      pageSize: myEvaluationsPageSize.value
    };

    console.log('请求我的评价列表参数:', params);
    const response = await getMyEvaluations(params);
    console.log('我的评价列表响应数据:', response);
    
    if (response.code === 0) {

      myEvaluations.value = response.data.items || [];
      console.log(myEvaluations.value[0].score)
      // console.log(myEvaluations.value.score)
      totalMyEvaluations.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取我的评价列表失败');
      myEvaluations.value = [];
      totalMyEvaluations.value = 0;
    }
  } catch (error) {
    console.error('获取我的评价列表失败:', error);
    ElMessage.error('网络错误，请重试');
    myEvaluations.value = [];
    totalMyEvaluations.value = 0;
  } finally {
    loadingMyEvaluations.value = false;
  }
};

// 获取同学评价列表
const fetchClassmateEvaluations = async () => {
  loadingClassmateEvaluations.value = true;
  try {
    const params = {
      studentId: userStore.userInfo.studentId,
    //   keyword: searchKeyword.value,
      page: classmateEvaluationsCurrentPage.value,
      pageSize: classmateEvaluationsPageSize.value
    };

    console.log('请求同学评价列表参数:', params);
    const response = await getClassmateEvaluations(params);
    console.log('同学评价列表响应数据:', response);
    
    if (response.code === 0) {
    //   classmateEvaluations.value = response.data.items || [];
      classmateEvaluations.value = (response.data.items || []).map(item => ({
        ...item,
        evaluatorName: '匿名用户' // 强制覆盖为匿名
      }));
      totalClassmateEvaluations.value = response.data.total || 0;

      
    } else {
      ElMessage.error(response.message || '获取同学评价列表失败');
      classmateEvaluations.value = [];
      totalClassmateEvaluations.value = 0;
    }
  } catch (error) {
    console.error('获取同学评价列表失败:', error);
    ElMessage.error('网络错误，请重试');
    classmateEvaluations.value = [];
    totalClassmateEvaluations.value = 0;
  } finally {
    loadingClassmateEvaluations.value = false;
  }
};

// 搜索同学评价
// const searchClassmateEvaluations = async () => {
//   classmateEvaluationsCurrentPage.value = 1;
//   await fetchClassmateEvaluations();
// };

// 打开评价模态框
const openEvaluationModal = async (target) => {
  console.log('Opening evaluation modal for:', target);
  currentTarget.value = target;
  console.log('Opening evaluation modal for:', currentTarget.value);
  resetForm();
  
  // // 加载最新的评价数据（如果有）
  // await loadEvaluationHistory();
  
  dialogVisible.value = true;
};

// 加载评价历史数据
// const loadEvaluationHistory = async () => {
//   try {
//     const targetId = currentTarget.value.studentId;

//     if (!targetId) {
//       ElMessage.error('请选择要评价的对象');
//       return;
//     }

//     const roleId = selectedType.value === "class" 
//       ? currentTarget.value.studentId 
//       : currentTarget.value.staffId;

//     const response = await getStudentEvaluation({
//       targetId: roleId,
//       targetType: selectedType.value
//     });

//     console.log('评价历史记录响应:', response);
    
//     if (response.code === 0 && response.data && response.data.list) {
//       const evaluations = response.data.list;
      
//       if (evaluations.length > 0) {
//         const latest = evaluations[0];
//         evaluationForm.value = {
//           score: latest.score || 5,
//           attitude: latest.attitude || 5,
//           ability: latest.ability || 5,
//           communication: latest.communication || 5,
//           content: latest.content || ''
//         };
//       }
//     }
//   } catch (error) {
//     console.error('加载评价历史失败:', error);
//   }
// };

// 查看我的评价详情
const viewMyEvaluation = (evaluation) => {
  myEvaluationDetail.value = { ...evaluation };
  console.log(myEvaluationDetail.value)
  myEvaluationDialogVisible.value = true;
};

// 查看同学评价详情
const viewClassmateEvaluation = (evaluation) => {
  classmateEvaluationDetail.value = { ...evaluation };
  classmateEvaluationDialogVisible.value = true;
};

// 提交评价
const submitEvaluation = async () => {
  try {
    const roleId = selectedType.value === "class" 
      ? currentTarget.value.studentId 
      : currentTarget.value.staffId;
    
    const params = {
      studentId: userStore.userInfo.studentId,
      targetId: roleId,
      targetType: selectedType.value,
      score: evaluationForm.value.score,
      attitude: evaluationForm.value.attitude,
      ability: evaluationForm.value.ability,
      communication: evaluationForm.value.communication,
      content: evaluationForm.value.content
    };

    console.log('提交评价参数:', params);
    const response = await EvaluationSubmit(params);
    console.log('提交评价响应:', response);
    
    if (response.code === 0) {
      dialogVisible.value = false;
      ElMessage.success('评价提交成功！');
      
      // 刷新我的评价列表
      if (mainTab.value === 'my-evaluations') {
        console.log("15151")
        await fetchMyEvaluations();
      }
    } else {
      ElMessage.error(response.message || '提交评价失败');
    }
  } catch (error) {
    console.error('提交评价失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

// 重置表单
const resetForm = () => {
  evaluationForm.value = {
    score: 5,
    attitude: 5,
    ability: 5,
    communication: 5,
    content: ''
  };
};

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchTargets();
};

const handleMyEvaluationsPageChange = (page) => {
  myEvaluationsCurrentPage.value = page;
  fetchMyEvaluations();
};

const handleClassmateEvaluationsPageChange = (page) => {
  classmateEvaluationsCurrentPage.value = page;
  fetchClassmateEvaluations();
};

// 初始化
onMounted(() => {
  
  fetchClassmateEvaluations();
});
</script>

<style scoped>
.evaluation-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background-color: #409eff;
  color: white;
}

/* 优化加载状态样式 */
.el-table .el-loading-mask {
  z-index: 100;
}

/* 评价历史记录样式 */
.evaluation-history {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #ebeef5;
}

.evaluation-item {
  background-color: #f9fafc;
  padding: 0.75rem;
  border-radius: 4px;
  margin-bottom: 0.75rem;
}

/* 评价详情样式 */
.evaluation-detail {
  margin-top: 1rem;
}

.score-display {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.score-label {
  width: 100px;
  color: #606266;
}
</style>